import os
import time
import pyautogui
from PIL import Image
import io
import win32clipboard

# 获取当前目录下所有图片文件
image_dir = os.getcwd()
image_files = [f for f in os.listdir(image_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))]

# 设置周期（秒）和最大尺寸
interval = 0.01
max_size = (1920, 1080)  # 设置最大宽高，保持等比缩放

# 将压缩的图片保存到剪贴板
def set_compressed_image_to_clipboard(image_path, quality=85, max_size=max_size):
    image = Image.open(image_path)
    
    # 等比缩放图片
    image.thumbnail(max_size, Image.LANCZOS)
    
    # 压缩图片
    output = io.BytesIO()
    image.convert('RGB').save(output, format='JPEG', quality=quality)
    data = output.getvalue()
    output.close()

    # 将JPEG数据转换为DIB格式并放入剪贴板
    bmp_data = Image.open(io.BytesIO(data))
    output_dib = io.BytesIO()
    bmp_data.convert('RGB').save(output_dib, format='BMP')
    data_dib = output_dib.getvalue()[14:]
    output_dib.close()

    # 设置剪贴板
    retries = 5
    for _ in range(retries):
        try:
            win32clipboard.OpenClipboard()
            win32clipboard.EmptyClipboard()
            win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data_dib)
            win32clipboard.CloseClipboard()
            break
        except Exception as e:
            print(f"Error: {e}")
            time.sleep(1)  # 等待1秒后重试
        finally:
            try:
                win32clipboard.CloseClipboard()
            except:
                pass

# 循环遍历图片并放入剪切板
for image_file in image_files:
    image_path = os.path.join(image_dir, image_file)
    
    # 将压缩的图片放入剪切板
    set_compressed_image_to_clipboard(image_path, quality=85)
    
    # 模拟按下 Ctrl+V 键
    pyautogui.hotkey('ctrl', 'v')
    
    # 模拟按下 Enter 键
    pyautogui.press('enter')
    
    # 等待一定时间
    time.sleep(interval)
